#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 错误处理
die() {
    echo -e "${RED}[错误] $1${NC}" >&2
    exit 1
}

# 获取本机IP地址
get_local_ip() {
    ip -o -4 addr show | awk '{print $4}' | cut -d'/' -f1 | grep -v '127.0.0.1' | head -n1
}

# 精准系统检测
detect_system() {
    # 检测群辉DSM
    if [ -f /etc/synoinfo.conf ] && [ -d /var/packages ]; then
        echo "dsm"
        return
    fi

    # 检测FNOS系统
    if grep -q "ID=debian" /etc/os-release && ls /vol1* &>/dev/null; then
        echo "fnos"
        return
    fi

    # 检测其他Debian系统
    if grep -q "ID=debian" /etc/os-release; then
        echo "debian"
        return
    fi

    # 其他Linux系统
    if [ -f /etc/os-release ]; then
        echo "linux"
        return
    fi

    echo "unknown"
}

# 检查Docker Compose可用性
check_docker_compose() {
    if command -v docker-compose &>/dev/null; then
        echo "docker-compose"
    elif docker compose version &>/dev/null; then
        echo "docker compose"
    else
        die "未找到Docker Compose"
    fi
}

# 检查端口占用
check_port() {
    local port=$1
    if command -v netstat &>/dev/null && netstat -tuln | grep -q ":${port} "; then
        die "端口 ${port} 已被占用"
    elif command -v ss &>/dev/null && ss -tuln | grep -q ":${port} "; then
        die "端口 ${port} 已被占用"
    fi
}

# 密码强度验证
validate_password() {
    local password=$1
    if [ ${#password} -lt 6 ]; then
        echo -e "${YELLOW}[警告] 密码长度建议至少6位${NC}"
        read -p "是否继续使用弱密码? (y/N): " confirm
        if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
            die "用户取消安装"
        fi
    fi
}

# 动态获取Docker目录（增强版）
get_docker_dir() {
    local system_type=$(detect_system)
    local dir=""

    case $system_type in
        "dsm")
            dir=$(find /volume* -maxdepth 1 -type d -name "docker" 2>/dev/null | head -n1)
            [ -z "$dir" ] && dir="/volume1/docker"
            ;;
        "fnos")
            dir=$(find /vol*/1000 -maxdepth 1 -type d -name "docker" 2>/dev/null | head -n1)
            [ -z "$dir" ] && dir="/vol1/1000/docker"
            ;;
        *)
            dir="/opt/docker"
            ;;
    esac

    dir=$(echo "$dir" | tr -d '\n\r' | sed 's/\/$//')
    mkdir -p "$dir" || die "无法创建目录 $dir"
    echo "$dir"
}

# 生成docker-compose.yml文件到指定目录
generate_docker_compose() {
    local target_dir=$1
    local data_dir=$2
    local port=$3
    local username=$4
    local password=$5
    
    cat > "${target_dir}/docker-compose.yml" << EOF
version: '3'

services:
  katelyatv:
    image: ghcr.io/katelya77/katelyatv:latest
    container_name: katelyatv
    restart: always
    ports:
      - "${port}:3000"
    environment:
      - USERNAME=${username}
      - AUTH_PASSWORD=${password}
      - NEXT_PUBLIC_STORAGE_TYPE=kvrocks
      - KVROCKS_URL=redis://kvrocks:6666
      - NEXT_PUBLIC_ENABLE_REGISTER=true
    depends_on:
      - kvrocks
    networks:
      - katelyatv-network

  kvrocks:
    image: apache/kvrocks:latest
    container_name: kvrocks
    restart: always
    ports:
      - "6666:6666"
    volumes:
      - ${data_dir}/katelyatv/data:/data
    networks:
      - katelyatv-network

networks:
  katelyatv-network:
    driver: bridge

volumes:
  kvrocks_data:
    driver: local
EOF
}

# 卸载功能
uninstall() {
    echo -e "${YELLOW}[警告] 即将卸载KatelyaTV${NC}"
    read -p "确认卸载? (y/N): " confirm
    if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
        echo "取消卸载"
        exit 0
    fi
    
    local data_dir=$(get_docker_dir)
    local katelyatv_dir="${data_dir}/katelyatv"
    
    if [ -f "${katelyatv_dir}/docker-compose.yml" ]; then
        cd "${katelyatv_dir}" || die "无法进入目录 ${katelyatv_dir}"
        local COMPOSE_CMD=$(check_docker_compose)
        $COMPOSE_CMD down 2>/dev/null
    else
        docker rm -f katelyatv kvrocks 2>/dev/null
    fi
    
    rm -rf "${katelyatv_dir}"
    echo -e "${GREEN}[√] KatelyaTV已卸载${NC}"
}

# 主安装流程
install_katelyatv() {
    # 获取动态目录
    local data_dir=$(get_docker_dir)
    local katelyatv_dir="${data_dir}/katelyatv"
    local COMPOSE_CMD=$(check_docker_compose)

    # 用户输入
    read -p "请输入KatelyaTV访问端口 [默认6091]: " port
    read -p "请输入管理员用户名 [默认admin]: " username
    read -p "请输入管理员密码 [默认admin111]: " password
    port=${port:-6091}
    username=${username:-admin}
    password=${password:-admin111}

    # 验证输入
    if ! [[ "$port" =~ ^[0-9]+$ ]] || [ "$port" -lt 1 ] || [ "$port" -gt 65535 ]; then
        die "无效端口: $port"
    fi
    check_port "$port"
    validate_password "$password"

    # 清理旧容器
    $COMPOSE_CMD down 2>/dev/null
    docker rm -f katelyatv kvrocks 2>/dev/null

    # 创建数据目录和katelyatv目录
    mkdir -p "${katelyatv_dir}/data" || die "无法创建数据目录"

    # 生成docker-compose文件到katelyatv目录
    echo -e "${BLUE}[信息] 生成docker-compose配置文件到 ${katelyatv_dir}...${NC}"
    generate_docker_compose "$katelyatv_dir" "$data_dir" "$port" "$username" "$password"

    # 进入目录并部署服务
    echo -e "${BLUE}[信息] 启动KatelyaTV服务...${NC}"
    cd "${katelyatv_dir}" || die "无法进入目录 ${katelyatv_dir}"
    $COMPOSE_CMD up -d || die "启动服务失败"

    # 验证部署
    sleep 5
    if ! docker ps | grep -q katelyatv; then
        docker logs katelyatv | head -n 20
        die "KatelyaTV容器启动失败"
    fi

    if ! docker ps | grep -q kvrocks; then
        docker logs kvrocks | head -n 20
        die "KVrocks容器启动失败"
    fi

    # 显示结果
    local ip=$(get_local_ip)
    echo -e "\n${GREEN}========== 部署成功 ==========${NC}"
    echo -e "系统类型: $(detect_system | tr '[:lower:]' '[:upper:]')"
    echo -e "访问地址: ${GREEN}http://${ip}:${port}${NC}"
    echo -e "用户名: ${YELLOW}${username}${NC}"
    echo -e "密码: ${YELLOW}${password}${NC}"
    echo -e "安装目录: ${katelyatv_dir}"
    echo -e "数据目录: ${katelyatv_dir}/data"
    echo -e "KVrocks端口: 6666"
    echo -e "Compose文件: ${katelyatv_dir}/docker-compose.yml"
    echo -e "\n管理命令:"
    echo -e "查看日志: ${YELLOW}cd ${katelyatv_dir} && ${COMPOSE_CMD} logs -f${NC}"
    echo -e "停止服务: ${YELLOW}cd ${katelyatv_dir} && ${COMPOSE_CMD} down${NC}"
    echo -e "重启服务: ${YELLOW}cd ${katelyatv_dir} && ${COMPOSE_CMD} restart${NC}"
}

# 检查Docker和Docker Compose
check_dependencies() {
    if ! command -v docker &>/dev/null; then
        die "请先安装Docker"
    fi
    echo -e "${GREEN}[√] Docker已安装 ($(docker --version | cut -d ' ' -f 3 | tr -d ','))${NC}"

    check_docker_compose >/dev/null
    echo -e "${GREEN}[√] Docker Compose可用${NC}"
}

# 主函数
main() {
    echo -e "${GREEN}
    ██╗  ██╗ █████╗ ████████╗███████╗██╗     ██╗   ██╗████████╗██╗   ██╗
    ██║ ██╔╝██╔══██╗╚══██╔══╝██╔════╝██║     ██║   ██║╚══██╔══╝██║   ██║
    █████╔╝ ███████║   ██║   █████╗  ██║     ██║   ██║   ██║   ██║   ██║
    ██╔═██╗ ██╔══██║   ██║   ██╔══╝  ██║     ██║   ██║   ██║   ██║   ██║
    ██║  ██╗██║  ██║   ██║   ███████╗███████╗╚██████╔╝   ██║   ╚██████╔╝
    ╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝   ╚══════╝╚══════╝ ╚═════╝    ╚═╝    ╚═════╝
    ${NC}"

    check_dependencies
    install_katelyatv
}

# 参数处理
case "${1:-}" in
    "uninstall")
        uninstall
        ;;
    "")
        main
        ;;
    *)
        echo "用法: $0 [uninstall]"
        exit 1
        ;;
esac